package com.nuoniu.sibanyun.service.erp.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.erp.ErpProcessRoute;
import com.nuoniu.sibanyun.entity.erp.ErpProcessRouteDetail;
import com.nuoniu.sibanyun.entity.production.ErpBomMain;
import com.nuoniu.sibanyun.entity.vo.ErpProcessRouteDetailVo;
import com.nuoniu.sibanyun.mapper.erp.ErpProcessRouteMapper;
import com.nuoniu.sibanyun.mapper.production.VBomMainMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpProcessRouteDetailService;
import com.nuoniu.sibanyun.service.erp.IErpProcessRouteService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 工艺路线 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2020-12-30
 */
@Service
public class ErpProcessRouteServiceImpl extends ServiceImpl<ErpProcessRouteMapper, ErpProcessRoute> implements IErpProcessRouteService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IErpProcessRouteDetailService processRouteDetailService;
    @Autowired
    private VBomMainMapper bomMainMapper;

    @Override
    public Page<ErpProcessRoute> getList(Page page, ErpProcessRoute processRoute) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<ErpProcessRoute> queryWrapper = new QueryWrapper();
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        queryWrapper.eq("account_id", accountService.getCurrentAccountId());
//        if(null != processRoute.getInventoryId()){
//            queryWrapper.eq("inventory_id", processRoute.getInventoryId());
//        }
        if(processRoute.getStatus() != null) {
            queryWrapper.eq("status", processRoute.getStatus());
        }
        if(processRoute.getExamineStatus() != null) {
            queryWrapper.eq("examine_status", processRoute.getExamineStatus());
        }
        if(StringUtils.isNotBlank(processRoute.getSearchKey())) {
            queryWrapper.and(wrapper -> wrapper.likeRight("code", processRoute.getSearchKey()).or().like("name", processRoute.getSearchKey()));
        }
        queryWrapper.orderByDesc("update_date");
        return page(page, queryWrapper);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveProcessRoute(ErpProcessRoute processRoute) {
        UserInfo userInfo = UserThreadLocal.get();
        LocalDateTime now = LocalDateTime.now();
        List<ErpProcessRouteDetail> processRouteDetails = processRoute.getProcessRouteDetails();
        ErpProcessRoute routeByCode = baseMapper.getByCode(userInfo.getCompanyId(), processRoute.getCode());
        if(routeByCode != null && (processRoute.getId() == null || !processRoute.getId().equals(routeByCode.getId()))) {
            throw new NuoNiuException("编码不能重复");
        }

        ErpProcessRoute routeByName = baseMapper.getByName(userInfo.getCompanyId(), processRoute.getName());
        if(routeByName != null && (processRoute.getId() == null || !processRoute.getId().equals(routeByName.getId()))) {
            throw new NuoNiuException("名称不能重复");
        }

        if(processRoute.getId() == null) {
            processRoute.setAccountId(accountService.getCurrentAccountId());
            processRoute.setCreateUserId(userInfo.getUserId());
            processRoute.setCompanyId(userInfo.getCompanyId());
            processRoute.setCreateUserName(userInfo.getRealName());
            processRoute.setCreateDate(now);
        }else {
            Integer userCount = bomMainMapper.getByPRId(processRoute.getId());
            if(userCount > 0) {
                throw new NuoNiuException("已在bom中使用,不能修改");
            }
        }
        processRoute.setUpdateDate(now);
        processRoute.setUpdateUserId(userInfo.getUserId());
        processRoute.setUpdateUserName(userInfo.getRealName());
        // 保存 主表
        Boolean result = saveOrUpdate(processRoute);
            if(result) {
                boolean haveFirst = false;
                boolean haveMiddle = false;
                boolean haveEnd = false;

                List<Long> detailIds = new ArrayList<>();
                for (ErpProcessRouteDetail detail: processRouteDetails) {
                    Integer workFlag = detail.getWorkFlag();
                    if(1 == workFlag) haveFirst=true;
                    if(3 == workFlag) haveMiddle=true;
                    if(2 == workFlag) haveEnd=true;
                    if (detail.getId() != null) {
                        detailIds.add(detail.getId());
                    }
                    detail.setPrId(processRoute.getId().intValue());
                    detail.setCompanyId(userInfo.getCompanyId());
                }
                int size = processRouteDetails.size();
                if(size > 0 && !haveFirst)throw new NuoNiuException("缺失首工序");
                if(size > 2 &&!haveMiddle)throw new NuoNiuException("缺失中间工序");
                if(size > 1 &&!haveEnd)throw new NuoNiuException("缺失尾工序");

                //删除多余明细
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("pr_id", processRoute.getId());
                if (detailIds != null && detailIds.size() > 0) {
                    wrapper.notIn("id", detailIds);
                    processRouteDetailService.remove(wrapper);
                } else {
                    processRouteDetailService.remove(wrapper);
                }
                //保存明细表
                processRouteDetailService.saveOrUpdateBatch(processRouteDetails);
        }

    }

    @Override
    public void examine(Long id, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        //1.校验
        if (null == id || null == status || status > 1 || status < 0)throw new NuoNiuException("参数错误");
        //2.查询
        ErpProcessRoute erpProcessRoute = getById(id);
        if (null == erpProcessRoute || !userInfo.getCompanyId().equals(erpProcessRoute.getCompanyId()))throw new NuoNiuException("参数错误,请选择正确的记录");
        //3.查询 使用情况（直接通过 查询BOM单 ）
        Integer userCount = bomMainMapper.getByPRId(id);
        if(userCount > 0) {
            throw new NuoNiuException("已在bom中使用,不能修改");
        }
        ErpProcessRoute processRoute = new ErpProcessRoute();
        processRoute.setExamineStatus(status);
        processRoute.setId(id);
        updateById(processRoute);
    }

    @Override
    public void delete(Long id) {
        Integer userCount = bomMainMapper.getByPRId(id);
        if(userCount > 0) {
            throw new NuoNiuException("已在bom中使用,不能删除");
        }

        processRouteDetailService.deleteByPRId(id);
        removeById(id);
    }

    @Override
    public List<ErpProcessRouteDetail> getDetailList(Integer id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("pr_id", id);
        wrapper.orderByAsc("work_order");
        return processRouteDetailService.list(wrapper);
    }

    @Override
    public List<ErpProcessRouteDetailVo> listErpProcessRouteDetailVo(Integer id) {
        return baseMapper.listErpProcessRouteDetailVo(id);
    }
}
